faApp.controller('ProductBaseCtrl',['$scope','productService','$location','$controller','$route','$routeParams',function($scope,productService,$location,$controller,$route,$routeParams) {
  $controller('BaseCtrl', {$scope: $scope});

  $scope.deleteProduct = function(id){
    productService.productDelete(id).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("产品删除成功！");
        if ($scope.pageChanged){$route.reload();}
        else $location.path("/product/list");
      }
    });
  };

  $scope.stopProduct = function(id,status){
    productService.productStop(id,status).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("产品已下架！");
        $route.reload();
      }
    });
  };

  $scope.productPassVerify = function(id){
    productService.productPassVerify(id).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("产品审核通过！");
        $route.reload();
      }
    });
  };
  
//提交审核
  $scope.addProductCheckVerify = function(id,type){
    //addCheckType  1为新增产品审核   2为修改费用审核 
    productService.addProductCheckVerify({"id":id,"addCheckType":type}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("产品提交审核成功！");
        $route.reload();
      }
    });
  };

  $scope.productDenyVerify = function(id,type){
    productService.productDenyVerify(id,type).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("产品审核已拒绝！");
        $route.reload();
      }
    });
  };

  $scope.productPassPublish = function(id){
    productService.productPassPublish(id).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("产品发布成功！");
        $route.reload();
      }
    });
  };

  $scope.showProductEstablish = function(id){
    $scope.estabItem = $scope.estabItem || {};
    $scope.estabItem.id = id;
    $scope.showEstablishaFormFlag = true;
  };

  $scope.productEstablish = function(id){
    if (!$scope.estagForm.$invalid){
      $scope.estabItem.pEstablishmentTimeStr += " 00:00:00";
      productService.productEstablish($scope.estabItem).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.alertNextPage("产品成立操作成功！");
          $route.reload();
        }
      });
    }else{
      alert("请先填写时间");
    }
  };
}]);

faApp.controller('ProductListCtrl',['$scope','productService','$location','$controller','$route','$routeParams','sessionService',function($scope,productService,$location,$controller,$route,$routeParams,sessionService) {
  $controller('ProductBaseCtrl', {$scope: $scope});

  $scope.ctrlName = "ProductListCtrl";
  $controller('BaseListCtrl', {$scope: $scope});

  $scope.products = [];
  $scope.loading = true;
  //获取页面类型，信托、资管
  $scope.t = $routeParams.t;

  // 判断当前用户是否有编辑产品解析报告的权限
  $scope.isAnalytics = false;

  var hasPage = 'hasPageProductListCtrl';

  angular.forEach(sessionService.getItem("user.access","").split(","), function(o){
    if(o == 'deepAnalyticsDetail.shtml' || o == 'all'){
      $scope.isAnalytics = true;
    }
  });

  $scope.changeProductType = function(){
    var tmp = "";
    $("[name='ptype']").each(function(){
      if($(this).attr("checked") == "checked"){
        tmp += $(this).val() + ",";
      }
    });
    if(tmp.length > 0){
      tmp = tmp.substring(0, tmp.length - 1);
    }else{
      //如果神马都没选，则还是显示默认页面类型
      tmp = $routeParams.t;
    }
    $scope.t = tmp;
    $scope.config['pTypeList'] = tmp;
  };

  $scope.$watch('config',function(newVal,oldVal,scope){
   
    //根据页面传入的信托、资管类型，添加查询条件
    if($scope.t != undefined){
      //$scope.searchMap.pType = $scope.t;
      $scope.config['pTypeList'] = $scope.t;
    }
    if($scope.config['pTypeList']==undefined||$scope.config['pTypeList']==''){
      $scope.config['pTypeList'] = "02,03";
    }
   if(newVal==oldVal)return;
    productService.productList($scope.config).then(function(json){
      $scope.products = json.projectList;
      $scope.pager = json.projectDTO;
      $scope.loading = false;
    });
  },true);

  $scope.searchMap['orderBy'] = $routeParams.orderBy || '',
    $scope.searchMap['orderByTag'] = $routeParams.orderByTag || '',
    $scope.config['orderBy'] = $routeParams.orderBy || '',
    $scope.config['orderByTag'] = $routeParams.orderByTag || '',

    $scope.changeWeightMap = {};
  $scope.productWeightMap = {};
  $scope.showChangeWeight = function(id){
    if (!$scope.hasAuth("btn","PRODUCT_RECOMMEND")){
      return;
    }

    $scope.changeWeightMap[id] = true;
  };
  $scope.changeWeight = function(id){
    productService.productRecommend({fpProjectId:id,recommendWeight:$scope.productWeightMap[id]}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("修改推荐状态成功！");
        $route.reload();
      }
    });
  };

  $scope.orderbyPositionMap = {};
  if (!$routeParams.orderBy && !$routeParams.orderByTag){
    $scope.orderbyPositionMap['weight'] = "0";
  }else{
    $scope.orderbyPositionMap[$routeParams.orderBy] = "0";
  }
  $scope.orderbyFreqMap = {"id":["desc","asc"],"weight":["desc"],"updateDate":["desc","asc"]};

  $scope.orderby = function(field){
    var freq = $scope.orderbyFreqMap[field];
    var old = $scope.orderbyPositionMap[field];
    $scope.orderbyPositionMap = {};
    if (old == undefined){
      $scope.orderbyPositionMap[field] = 0;
    }else{
      $scope.orderbyPositionMap[field] = old + 1;
      if ($scope.orderbyPositionMap[field] >= freq.length){
        $scope.orderbyPositionMap[field] = 0;
      }
    }
    if (field == "weight"){
      $scope.config.orderBy = "";
      $scope.config.orderByTag = "";
    }else{
      $scope.config.orderBy = field;
      $scope.config.orderByTag = freq[$scope.orderbyPositionMap[field]];
    }
  };

  $scope.chkProjectAll = function(){
    if($("#chkProjectAll").attr("checked") == "checked"){
      $("[name='chkProject']").attr("checked","checked");
    }else{
      $("[name='chkProject']").attr("checked",false);
    }
  }

  $scope.upDate = function(){
    var allCheck = $("[name='chkProject']");
    var pids = "";
    $("[name='chkProject']").each(function(){
      if($(this).attr("checked") == "checked"){
          pids += $(this).val() + ",";
        }
    });
     if(pids.length > 0){
      if(!confirm("确认更新吗?")){
        return;
      }
      pids = pids.substring(0, pids.length - 1);
      var product = {
        "ids":pids
      }
      //修改产品的更新时间
      productService.productEdit(product).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("更新成功！");
          $route.reload();
        }
      });
    }else{
      alert("请选择一个产品！");
    }
  }

  $scope.sendEmail = function(){
    var allCheck = $("[name='chkProject']");
    var pids = "";
    var firstVal = "";
    var isFirst = 0;
    var error = "";
    $("[name='chkProject']").each(function(){
      if($(this).attr("checked") == "checked"){
        if($(this).attr("accessId") == undefined || $(this).attr("accessId") == ""){
          error += "产品未选择供应方，产品ID：" + $(this).val() + "！\n";
          return false;
        }else{
          if(isFirst == 0){
            isFirst = 1;
            firstVal = $(this).attr("accessId") || "-1";
          }else{
            if(firstVal != $(this).attr("accessId")){
              error = "所选产品不属于同一供应方！";
              return false;
            }
          }
          pids += $(this).val() + ",";
        }
      }
    });
    if(error.length > 0){
      alert(error);
      return;
    }
    if(pids.length > 0){
      if(!confirm("确认发送吗?")){
        return;
      }

      pids = pids.substring(0, pids.length - 1);
      productService.sendEmail(pids).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("发送成功！");
          $scope.alertNextPage("发送成功！");
        }
      });
    }else{
      alert("请选择一个产品！");
    }
  };

  $scope.isShowCopyTypeLayer = false;
  $scope.copyId = "";
  $scope.pt = "";
  $scope.isCopyReport = false;

  $scope.showCopyTypeLayer = function(id,pt){
    $scope.isShowCopyTypeLayer = true;
    $scope.copyId = id;
    $scope.pt = pt;
  }


  $scope.search = function(notsave){
    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

    var p = sessionService.getItem(hasPage) || 0;
    if(p > 0){
      $scope.config.pageNo = p;
      sessionService.removeItem(hasPage);
    }else{
      $scope.config.pageNo = 1;
    }

    !notsave && $scope.saveLastSearchConfig();
  };

  $scope.toViewPage = function(id, address){
    if(id){
      sessionService.setItem(hasPage, $scope.pager.pageNo);

      var url = address + 'id=' + id + '&t=' + $scope.t;
      $location.url(url);
    }
  }

  $scope.getLastSearchConfig();
  $scope.search();

}]);

faApp.controller('ProductQDListCtrl',['$scope','productService','$location','$controller','$route','$routeParams','sessionService',function($scope,productService,$location,$controller,$route,$routeParams,sessionService) {
  $controller('ProductBaseCtrl', {$scope: $scope});
  $scope.ctrlName = "ProductQDListCtrl";
  $controller('BaseListCtrl', {$scope: $scope});
  
  $scope.sortSelected="1";

  $scope.products = [];
  $scope.loading = true;

  $scope.showDataPreview = false;
  $scope.dataPreview=[];
  //当前预览哪个文件
  $scope.changeShowDataPreview =function(f,v){
    $scope.showDataPreview=f;
    if(v){
      $scope.dataPreview=v;
    }else{
      $scope.dataPreview=[];
    }
  }
  //获取页面类型，信托、资管   
  $scope.t = $routeParams.t;
  if(!$scope.t){//默认全部
    $scope.t="02,03,06,07";
  }

  //产品名字
  $scope.config.pShortName=$routeParams.name?$routeParams.name:"";
  // 判断当前用户是否有编辑产品解析报告的权限
  $scope.isAnalytics = false;

  angular.forEach(sessionService.getItem("user.access","").split(","), function(o){
    if(o == 'deepAnalyticsDetail.shtml' || o == 'all'){
      $scope.isAnalytics = true;
    }
  });

  $scope.changeProductType = function(){
    var tmp = "";
    $("[name='ptype']").each(function(){
      if($(this).attr("checked") == "checked"){
        tmp += $(this).val() + ",";
        console.log(tmp);
      }
    });
    if(tmp.length > 0){
      tmp = tmp.substring(0, tmp.length - 1);
    }else{
      //如果神马都没选，则还是显示默认页面类型
      tmp = "";
    }
    $scope.t = tmp;
    $scope.config['pTypeList'] = tmp;
    console.log( $scope.config['pTypeList']);
  };
  $scope.changeProductTypeQuery = function(v){
    $scope.t = v;
    $scope.config['pTypeList'] = v;
    console.log( $scope.config['pTypeList']);
  };
    $scope.changeQueryType = function(v,t){
      var tmp = "";
      if(t!=true){
        $("[name="+v+"]").eq(0).removeAttr("checked");
      }
      $("[name="+v+"]").each(function(){
        if($(this).attr("checked") == "checked"){
          //t==true 为不限   清空所有条件和其他选中
          if($(this).val()==''&&t==true){
            temp="";
            $scope.config[v] = tmp;
            //循环清空复选框
            $("[name="+v+"]").removeAttr("checked");
            $("[name="+v+"]").eq(0).attr("checked","checked");
            return;
          }else{
            tmp += $(this).val() + ",";
            console.log(tmp);
          }
        }
      });
      if(tmp.length > 0){
        tmp = tmp.substring(0, tmp.length - 1);
      }else{
        //如果神马都没选，则还是显示默认页面类型
        tmp = "";
      }
      $scope.config[v] = tmp;
      console.log( $scope.config[v]);
    };
    $scope.changeProductSortBy = function(by){
      if(by){
        $scope.config.pageNo = 1;
        $scope.config.orderParameter = '';
        $scope.config.orderType = '';
        $scope.config.pRabateProfitParameter = '';
        $scope.config.pAnnualRevenueExpectParameter = '';
        if(by == '02'){
          $scope.config.pRabateProfitParameter = 'true';
        }else if(by == '03'){
          $scope.config.pAnnualRevenueExpectParameter = 'true';
        }else if(by == '04'){
          $scope.config.orderParameter = '01';
          $scope.config.orderType = '02';
        }else if(by == '05'){
          $scope.config.orderParameter = '03';
          $scope.config.orderType = '01';
        }
        $scope.productSort = by;
      }
    }
    //根据页面传入的信托、资管类型，添加查询条件
    if($scope.t != undefined){
      //$scope.searchMap.pType = $scope.t;
      $scope.config['pTypeList'] = $scope.t;
    }
    if($scope.config['pTypeList']==undefined||$scope.config['pTypeList']==''){
      $scope.config['pTypeList'] = "02,03,06,07";
    }
  $scope.$watch('config',function(){
    productService.productQDList($scope.config).then(function(json){
      $scope.products = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true);

  $scope.searchMap['orderBy'] = 'id',
    $scope.searchMap['orderByTag'] = 'desc',
    $scope.config['orderBy'] = 'id',
    $scope.config['orderByTag'] = 'desc',

    $scope.changeWeightMap = {};
  $scope.productWeightMap = {};
  $scope.showChangeWeight = function(id){
    if (!$scope.hasAuth("btn","PRODUCT_RECOMMEND")){
      return;
    }

    $scope.changeWeightMap[id] = true;
  };
  $scope.changeWeight = function(id){
    productService.productRecommend({fpProjectId:id,recommendWeight:$scope.productWeightMap[id]}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("修改推荐状态成功！");
        $route.reload();
      }
    });
  };

  $scope.orderbyPositionMap = {};
  if (!$routeParams.orderBy && !$routeParams.orderByTag){
    $scope.orderbyPositionMap['weight'] = "0";
  }else{
    $scope.orderbyPositionMap[$routeParams.orderBy] = "0";
  }
  $scope.orderbyFreqMap = {"id":["desc","asc"],"weight":["desc"],"updateDate":["desc","asc"]};

  $scope.orderby = function(field){
    var freq = $scope.orderbyFreqMap[field];
    var old = $scope.orderbyPositionMap[field];
    $scope.orderbyPositionMap = {};
    if (old == undefined){
      $scope.orderbyPositionMap[field] = 0;
    }else{
      $scope.orderbyPositionMap[field] = old + 1;
      if ($scope.orderbyPositionMap[field] >= freq.length){
        $scope.orderbyPositionMap[field] = 0;
      }
    }
    if (field == "weight"){
      $scope.config.orderBy = "";
      $scope.config.orderByTag = "";
    }else{
      $scope.config.orderBy = field;
      $scope.config.orderByTag = freq[$scope.orderbyPositionMap[field]];
    }
  };

  $scope.chkProjectAll = function(){
    if($("#chkProjectAll").attr("checked") == "checked"){
      $("[name='chkProject']").attr("checked","checked");
    }else{
      $("[name='chkProject']").attr("checked",false);
    }
  }

  $scope.sendEmail = function(){
    var allCheck = $("[name='chkProject']");
    var pids = "";
    var firstVal = "";
    var isFirst = 0;
    var error = "";
    $("[name='chkProject']").each(function(){
      if($(this).attr("checked") == "checked"){
        if($(this).attr("accessId") == undefined || $(this).attr("accessId") == ""){
          error += "产品未选择供应方，产品ID：" + $(this).val() + "！\n";
          return false;
        }else{
          if(isFirst == 0){
            isFirst = 1;
            firstVal = $(this).attr("accessId") || "-1";
          }else{
            if(firstVal != $(this).attr("accessId")){
              error = "所选产品不属于同一供应方！";
              return false;
            }
          }
          pids += $(this).val() + ",";
        }
      }
    });
    if(error.length > 0){
      alert(error);
      return;
    }
    if(pids.length > 0){
      if(!confirm("确认发送吗?")){
        return;
      }

      pids = pids.substring(0, pids.length - 1);
      productService.sendEmail(pids).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("发送成功！");
          $scope.alertNextPage("发送成功！");
        }
      });
    }else{
      alert("请选择一个产品！");
    }
  };

  $scope.isShowCopyTypeLayer = false;
  $scope.copyId = "";
  $scope.pt = "";
  $scope.isCopyReport = false;

  $scope.showCopyTypeLayer = function(id,pt){
    $scope.isShowCopyTypeLayer = true;
    $scope.copyId = id;
    $scope.pt = pt;
  }

}]);

faApp.controller('ProductQDViewCtrl',['$scope','$sce','productService','$location','$controller','$route','$routeParams','sessionService',function($scope,$sce,productService,$location,$controller,$route,$routeParams,sessionService) {
  $controller('ProductBaseCtrl', {$scope: $scope});
  $scope.id = $routeParams.id;
  productService.productQdQuery($scope.id).then(function(json){
    $scope.project = json.bean;
    $scope.project.summary=$sce.trustAsHtml($scope.project.summary);
  });

}]);

faApp.controller('ProductAddCtrl',['$scope', 'productService','reportService','$location','$controller','$timeout','companyService','supplierService','faService','$route','$filter','$routeParams',function($scope,productService,reportService,$location,$controller,$timeout,companyService,supplierService,faService,$route,$filter,$routeParams) {
  $controller('BaseCtrl', {$scope: $scope});


  $scope.product = {pMinimumAmountTmp:100,pRealSubscriptionAmount:0,pRealSubscriptionShare:0,pType:"02",pInvestType:"01",pPublicArea:"00",pSaleStatus:"03",pPaymentInterestType:"03",pEndEarlyIdentification:"0",pProgressiveAmountTmp:10,fpCorpId:0,fpProjectCorpType:'02',flagRaised:true};

    $scope.showXcxsearchnoRecord = false;

    $scope.pLabelItem = {};
    $scope.proserieslist = [];

  $scope.loading = true;
  $scope.pathText = "新增产品";
  $scope.pPublicAreaModel = $scope.publicAreaModel;
  if ($scope.pPublicAreaModel[0].value != "00")$scope.pPublicAreaModel.unshift({value:"00",text:"全国"});
  $scope.companys = [];
  $scope.companysMap = {};
  $scope.pid = $routeParams.id;

  $scope.supplierListOfProduct = [];
  $scope.accessNameOfCompany = "";

  $scope.t = $routeParams.t;
  $scope.outproduct={};
  if($routeParams.outProductId!=undefined){
    $scope.product.outProductId=$routeParams.outProductId;
  }
  if($routeParams.productName!=undefined){
    $scope.product.pName=$routeParams.productName;
    $scope.product.pFullName=$routeParams.productName;
  }

  //默认能竞价
  $scope.product.flagBidding=false;


  // 复制产品时，是否同时复制产品解析报告
  $scope.ct = $routeParams.ct;

  // 复制年化及佣金的数据
  $scope.projectAnnualRevenue = [];
  $scope.projectRabateList = [];
  $scope.attachs = [];

  // 复制产品解析报告
  $scope.report = {};

  $scope.allTjzls = {};

    $scope.openSerarnoWin = function () {
        productService.xcxSearchNoRecordList().then(function (json) {

            if (json.statusCode) {
                alert("出错了:" + json.statusCode);
            } else {
                $scope.showXcxsearchnoRecord = true;
                $scope.searchnolist = json.list;
            }
        });

    }
    $scope.getXcxsearchNoRecord = function (d) {
      console.info(d)
        $scope.product.pXcxSerarnoKeyword = d.keyword;

        $scope.showXcxsearchnoRecord = false;
    }

  if($scope.pid != undefined && $scope.pid.length > 0){
    //如果有值，则说明是点了复制按钮，则根据ID加载产品
    productService.productQuery($scope.pid).then(function(json){
      $scope.product = json.project;
      $scope.product.pLinkCode = $scope.product.pCode;
      $scope.product.pIssuingScaleTmp = $scope.product.pIssuingScale / 100000000;
      $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale / 100000000;
      $scope.product.pProgressiveAmountTmp = $scope.product.pProgressiveAmount / 10000;
      $scope.product.pMinimumAmountTmp = $scope.product.pMinimumAmount / 10000;
      $scope.product.pSaleTimeStartStr = $filter("date")($scope.product.pSaleTimeStart,"yyyy-MM-dd");
      $scope.product.pRaiseTime = $filter("date")($scope.product.pRaiseTime,"yyyy-MM-dd");

      $scope.product.pLetterTime = $filter("date")($scope.product.pLetterTime,"yyyy-MM-dd");
      $scope.product.pNoticeTime = $filter("date")($scope.product.pNoticeTime,"yyyy-MM-dd");
      if(json.project.pLabel) {
          var pLabelArr = json.project.pLabel.split(",");
          for(var i =0; i<pLabelArr.length; i++) {
              if (pLabelArr[i] == '23') {
                  $scope.pLabelItem.pLabel23 = '23'
              }
              if (pLabelArr[i] == '1') {
                  $scope.pLabelItem.pLabel1 = '1'
              }
              if (pLabelArr[i] == '2') {
                  $scope.pLabelItem.pLabel2 = '2'
              }
              if (pLabelArr[i] == '3') {
                  $scope.pLabelItem.pLabel3 = '3'
              }
              if (pLabelArr[i] == '4') {
                  $scope.pLabelItem.pLabel4 = '4'
              }
              if (pLabelArr[i] == '5') {
                  $scope.pLabelItem.pLabel5 = '5'
              }
              if (pLabelArr[i] == '6') {
                  $scope.pLabelItem.pLabel6 = '6'
              }
              if (pLabelArr[i] == '7') {
                  $scope.pLabelItem.pLabel7 = '7'
              }
              if (pLabelArr[i] == '8') {
                  $scope.pLabelItem.pLabel8 = '8'
              }
              if (pLabelArr[i] == '9') {
                  $scope.pLabelItem.pLabel9 = '9'
              }
              if (pLabelArr[i] == '10') {
                  $scope.pLabelItem.pLabel10 = '10'
              }
              if (pLabelArr[i] == '11') {
                  $scope.pLabelItem.pLabel11 = '11'
              }
              if (pLabelArr[i] == '12') {
                  $scope.pLabelItem.pLabel12 = '12'
              }
              if (pLabelArr[i] == '13') {
                  $scope.pLabelItem.pLabel13 = '13'
              }
              if (pLabelArr[i] == '14') {
                  $scope.pLabelItem.pLabel14 = '14'
              }
              if (pLabelArr[i] == '15') {
                  $scope.pLabelItem.pLabel15 = '15'
              }
              if (pLabelArr[i] == '16') {
                  $scope.pLabelItem.pLabel16 = '16'
              }
              if (pLabelArr[i] == '17') {
                  $scope.pLabelItem.pLabel17 = '17'
              }
              if (pLabelArr[i] == '18') {
                  $scope.pLabelItem.pLabel18 = '18'
              }
              if (pLabelArr[i] == '19') {
                  $scope.pLabelItem.pLabel19 = '19'
              }
              if (pLabelArr[i] == '22') {
                  $scope.pLabelItem.pLabel22 = '22'
              }
          }
      }

      $scope.proserieslist = json.fpProjectSeriesList;

      $scope.product.image = $scope.product.pImageUri;
      $scope.product.fpCorpId = "0";
      $scope.product.fpProjectCorpType = "02";
      if($scope.product.tjzls!=undefined){
        angular.forEach($scope.product.tjzls.split(","),function(o){
          $scope.allTjzls[o] = true;
        });
      }
      // 复制年化及佣金的数据
      $scope.projectAnnualRevenue = json.projectAnnualRevenueList;
      $scope.projectRabateList = json.projectRabateList;


      if($scope.product.projectExpandDTO!=undefined){
        $scope.product.peLogoUri=$scope.product.projectExpandDTO.peLogoUri;
        $scope.product.peHomeLogoUri=$scope.product.projectExpandDTO.peHomeLogoUri;
        delete $scope.product.projectExpandDTO;
      }

      delete $scope.product.pSaleTimeStart;
      delete $scope.product.pSaleTimeEnd;
      delete $scope.product.pEstablishmentTime;
      delete $scope.product.pCode;

      $scope.product.pRealSubscriptionAmount = 0;
      $scope.product.pRealSubscriptionShare = 0;
      //delete $scope.product.pRealSubscriptionAmount;
      //delete $scope.product.pRealSubscriptionShare;
    });

    // 加载原产品附件的数据
    productService.productAttachList($scope.pid).then(function(json){
      $scope.attachs = json.projectAttachmentsList;
    });

    // 如果选择复制 产品解析报告，则在此处先加载原产品的解析报告
    if($scope.ct){
      reportService.deepAnalyticsDetail($scope.pid).then(function(json){
        if(json.dto){
          $scope.report = json.dto || {};
          delete $scope.report.fpProductId;
          delete $scope.report.fpProductStatus;
          // delete $scope.report.id;
        }
      });
    }
  } else {
      productService.proSeriesList().then(function(json){
          $scope.proserieslist = json.fpProjectSeriesList;
      })
  }

  companyService.companyList().then(function(json){
    $scope.companys = json.list;
    angular.forEach($scope.companys,function(o){
      $scope.companysMap[o.id] = o;
    });
  });
    $scope.queryAccessCompany="";
  $scope.$watch('queryAccessCompany',function(){
     supplierService.supplierList({accessCompany:$scope.queryAccessCompany}).then(function(json){
        $scope.supplierListOfProduct = json.list;
      });
  },true);
  $scope.product.pSummary = "<div style='width:1000px;'><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='mjzh'></a>募集账号</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='bcsm'></a>补充说明</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='cpys'></a>产品优势</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='fxkz'></a>风险控制</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='hkly'></a>还款来源</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='zjyt'></a>资金用途</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='rzf'></a>融资方</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='dbf'></a>担保方</li><li style=''>---输入内容---</li></ul></div>";

  $scope.onSelectChange = function(){
    for (var i=0;i<$scope.supplierListOfProduct.length;i++){
      if($scope.supplierListOfProduct[i]['id'] == $scope.product.pAccessId){
        $scope.accessNameOfCompany = $scope.supplierListOfProduct[i]['accessName'];
        break;
      }
    }
  };

  $scope.save = function(){
    var pLabel="";
    if($scope.pLabelItem.pLabel23 && $scope.pLabelItem.pLabel23=='0') {
        pLabel+="23,";
    }
    if($scope.pLabelItem.pLabel1 && $scope.pLabelItem.pLabel1=='1') {
        pLabel+="1,";
    }
    if($scope.pLabelItem.pLabel2 && $scope.pLabelItem.pLabel2=='2') {
        pLabel+="2,";
    }
    if($scope.pLabelItem.pLabel3 && $scope.pLabelItem.pLabel3=='3') {
        pLabel+="3,";
    }
    if($scope.pLabelItem.pLabel4 && $scope.pLabelItem.pLabel4=='4') {
        pLabel+="4,";
    }
    if($scope.pLabelItem.pLabel5 && $scope.pLabelItem.pLabel5=='5') {
        pLabel+="5,";
    }
    if($scope.pLabelItem.pLabel6 && $scope.pLabelItem.pLabel6=='6') {
        pLabel+="6,";
    }
    if($scope.pLabelItem.pLabel7 && $scope.pLabelItem.pLabel7=='7') {
        pLabel+="7,";
    }
    if($scope.pLabelItem.pLabel8 && $scope.pLabelItem.pLabel8=='8') {
        pLabel+="8,";
    }
    if($scope.pLabelItem.pLabel9 && $scope.pLabelItem.pLabel9=='9') {
        pLabel+="9,";
    }
    if($scope.pLabelItem.pLabel10 && $scope.pLabelItem.pLabel10=='10') {
        pLabel+="10,";
    }
    if($scope.pLabelItem.pLabel11 && $scope.pLabelItem.pLabel11=='11') {
        pLabel+="11,";
    }
    if($scope.pLabelItem.pLabel12 && $scope.pLabelItem.pLabel12=='12') {
        pLabel+="12,";
    }
    if($scope.pLabelItem.pLabel13 && $scope.pLabelItem.pLabel13=='13') {
        pLabel+="13,";
    }
    if($scope.pLabelItem.pLabel14 && $scope.pLabelItem.pLabel14=='14') {
        pLabel+="14,";
    }
    if($scope.pLabelItem.pLabel15 && $scope.pLabelItem.pLabel15=='15') {
        pLabel+="15,";
    }
    if($scope.pLabelItem.pLabel16 && $scope.pLabelItem.pLabel16=='16') {
        pLabel+="16,";
    }
    if($scope.pLabelItem.pLabel17 && $scope.pLabelItem.pLabel17=='17') {
        pLabel+="17,";
    }
      if($scope.pLabelItem.pLabel18 && $scope.pLabelItem.pLabel18=='18') {
          pLabel+="18,";
      }
      if($scope.pLabelItem.pLabel19 && $scope.pLabelItem.pLabel19=='19') {
          pLabel+="19";
      }
      if($scope.pLabelItem.pLabel22 && $scope.pLabelItem.pLabel22=='22') {
          pLabel+="22";
      }

    console.info("产品标签:"+pLabel)
    if(pLabel && pLabel.substr(pLabel.length-1,1).indexOf(",")>-1) {
        pLabel = pLabel.substr(0, pLabel.length-1);
    }
    $scope.product.pLabel = pLabel;

    if (!$scope.form.$invalid){
      $scope.selectTjzls = [];
      var flag = false;
      for (var i in $scope.allTjzls){
        if ($scope.allTjzls[i]){
          flag = true;
          $scope.selectTjzls.push(i);
        }
      }
      if (!flag){
        alert("请勾选提交资料");
        return;
      }
      $scope.product.id = "";
      $scope.product.pType = $scope.t;
      //$scope.product.pIssuingScale = $scope.product.pIssuingScaleTmp * 100000000;
      $scope.product.pIssuingScale = 0;

      $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale * 100000000;
      $scope.product.pProgressiveAmount = $scope.product.pProgressiveAmountTmp * 10000;
      $scope.product.pMinimumAmount = $scope.product.pMinimumAmountTmp * 10000;
      if($scope.t != undefined && $scope.t == "02"){
        $scope.product.pInvestOwnerId && ($scope.product.pInvestOwner = $scope.companysMap[$scope.product.pInvestOwnerId]['cShortName']);
      }
      $scope.product.pInvestOwnerId = $scope.product.pInvestOwnerId || -1;
      if($scope.product.pInvestOwnerId == -1 && $scope.t == "02"){
        $scope.product.pInvestOwner = "";
      }

      if($scope.ct && $scope.report.id){
        $scope.product.copyType = "01";
      }

      $scope.product.tjzls=$scope.selectTjzls.join(",");

      productService.productAdd($scope.product).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
          if($scope.product.pAllIssuingScale>10000){
            $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale / 100000000;
          }
        }else{

          //产品录入成功之后，如果是复制操作则把年化佣金、附件同时保存到数据库。
          if($scope.pid != undefined && $scope.pid.length > 0){
            if($scope.projectAnnualRevenue.length > 0 && $scope.projectRabateList.length > 0){
              $scope.formData = {pId:[],pRebateType:[],pStartAmount:[],pEndAmount:[],pAnnualRevenueExpect:[],pIsAgreement:[],pRabateProfit:[],pCorePrice:[],pCostPrice:[],pSellingPrice:[],pBackRabateProfit:[],pCoreBackPrice:[],pCostBackPrice:[],pBackSellingPrice:[]};
              angular.forEach($scope.projectAnnualRevenue,function(o,i){
                //产品ID
                $scope.formData['pId'].push(json.projectDTO.id);
                //返佣类型，01：百分比
                $scope.formData['pRebateType'].push("01");
                //起始金额
                $scope.formData['pStartAmount'].push(o['pStartAmount']);
                // 结束金额
                $scope.formData['pEndAmount'].push(o['pEndAmount']);
                // 预期年化率
                $scope.formData['pAnnualRevenueExpect'].push(o['pAnnualRevenueExpect']);
                // 返佣率
                $scope.formData['pRabateProfit'].push($scope.projectRabateList[i]['pRabateProfit'] || 0);
                // 核心价
                $scope.formData['pCorePrice'].push($scope.projectRabateList[i]['pCorePrice'] || 0);
                // 成本价
                $scope.formData['pCostPrice'].push($scope.projectRabateList[i]['pCostPrice'] || 0);
                // 机构价
                $scope.formData['pSellingPrice'].push($scope.projectRabateList[i]['pSellingPrice'] || 0);

                // 后端挂网价
                $scope.formData['pBackRabateProfit'].push($scope.projectRabateList[i]['pBackRabateProfit'] || 0);
                // 后端核心价
                $scope.formData['pCoreBackPrice'].push($scope.projectRabateList[i]['pCoreBackPrice'] || 0);
                // 后端成本价
                $scope.formData['pCostBackPrice'].push($scope.projectRabateList[i]['pCostBackPrice'] || 0);
                // 后端机构价
                $scope.formData['pBackSellingPrice'].push($scope.projectRabateList[i]['pBackSellingPrice'] || 0);




                // 是否协议
                $scope.formData['pIsAgreement'].push($scope.projectRabateList[i]['pIsAgreement']);
              });
              $scope.formData2 = {id:json.projectDTO.id};
              for (k in $scope.formData){
                $scope.formData2[k] = $scope.formData[k].join(",");
              }
              productService.productProfitUpdate($scope.formData2).then(function(json){
                if (json.statusCode){
                  alert("保存年化及佣金时，出错了:" + json.statusCode);
                }
              });
            }

            if($scope.attachs.length > 0){
              // 保存附件的数据
              $scope.formDataAttach = {fName:[],fileUrl:[],fileType:[]};
              angular.forEach($scope.attachs,function(o,i){
                if (o['fName'] && o['fPath'] && o['fType']){
                  $scope.formDataAttach['fName'].push(o['fName']);
                  $scope.formDataAttach['fileUrl'].push(o['fPath']);
                  $scope.formDataAttach['fileType'].push(o['fType']);
                }
              });
              $scope.formData2Attach = {pId:json.projectDTO.id};
              for (k in $scope.formDataAttach){
                $scope.formData2Attach[k] = $scope.formDataAttach[k].join(",");
              }
              productService.productAttachUpdate($scope.formData2Attach).then(function(json){
                if (json.statusCode){
                  alert("保存附件时，出错了:" + json.statusCode);
                }
              });
            }

            // 如果选择复制 产品解析报告，则在此处先加载原产品的解析报告
            if($scope.ct && $scope.report.id){
              delete $scope.report.id;
              $scope.report.fpProductId = json.projectDTO.id;
              $scope.report.fpProductStatus = "2";
              reportService.deepAnalyticsSave($scope.report).then(function(json){
                if (json.statusCode){
                  alert("出错了:" + json.statusCode);
                }
              });
            }
          }
          $scope.alertNextPage("产品录入成功!");
          $location.path("/product/edit").search({id:json.projectDTO.id,t:$scope.t});
        }
      });
    }else{
      if ($scope.product.pSummary == undefined || !$scope.product.pSummary){
        alert("请填写产品简介");
      }else alert("请完整填写表单");
    }
  };
//  $scope.onUploadFile({
//    showMessage : function(m){ alert(m); },
  //   onComplete:function(f,response){
  //     if (response.statusCode == "0000") {
//        $scope.product.image = response.attribute.fileUrl;
//        $scope.$apply();
//      } else {
  //       alert('上传失败');
  //     }
  //   }
  // });
  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response,id){
      id--;
      if (response.statusCode == "0000") {
        if(id==0){
          $scope.product.image = response.attribute.fileUrl;
        }else if(id==1){
          $scope.product.peLogoUri= response.attribute.fileUrl;
        }else if(id==2){
          $scope.product.peHomeLogoUri= response.attribute.fileUrl;
        }
        $scope.$apply();
      } else {
        alert('上传失败');
      }
    }
  });

}]);

faApp.controller('ProSeriesCtrl',['$scope','productService','$location','$controller','$routeParams','$filter',function($scope,productService,$location,$controller,$routeParams,$filter) {
  $scope.proSeriesItem = {}
  $scope.proSeriesSave = function () {
    if(!$scope.myform.$invalid) {
        productService.proSeriesAdd($scope.proSeriesItem).then(function(json){
            console.info("新增产品系列")
          if(json.statusCode == '2003') {
              alert("产品系列已存在!")
          } else {
              $scope.proserieslist.unshift($scope.proSeriesItem);

              alert("产品系列新增成功!");
              $scope.$parent.showProSeriesFlag = false;

              $scope.proSeriesItem = {}
          }
        })
    }
  }

    $scope.proSeriesDelete = function (d, $index) {
        productService.proSeriesDelete(d).then(function(json){
            console.info("新增产品系列")
            if(json.statusCode == '2002') {
                alert("参数缺失!")
            } else if(json.statusCode == '5001'){
                alert("数据已被引用，不可删除!")
            } else {
                alert("删除成功!");
                $scope.proserieslist.splice($index, 1)
                if($scope.product.pSeries==d.proSeriesName) {
                    $scope.product.pSeries = '';
                }
            }


        })
    }
}]);

faApp.controller('ProductEditCtrl',['$scope','productService','$location','$controller','$routeParams','$filter','companyService','sessionService',function($scope,productService,$location,$controller,$routeParams,$filter,companyService,sessionService) {

  $scope.id = $routeParams.id;
  $scope.t = $routeParams.t;
  $scope.tabUrl = {};
  $scope.tabUrlMap = {
    viewUrl : "#/product/view?id=" + $scope.id,
    baseUrl : "#/product/base?id=" + $scope.id,
    saleprocessUrl: "#/product/saleProcess?id=" + $scope.id,
    profitUrl : "#/product/profit?id=" + $scope.id,
    attachmentUrl : "#/product/attach?id=" + $scope.id,
    roadVideo : "#/product/video?id=" + $scope.id
  };

  $scope.changeTab = function(tab){
    $scope.tabUrl[tab] = $scope.tabUrlMap[tab];
    sessionService.setItem("lastProductTab",tab);
  };

  var lastProductTab = sessionService.getItem('lastProductTab') || 'viewUrl';
  $scope.changeTab('viewUrl');

  $scope.pathText = $scope.id ? "修改产品" : "新建产品";

  angular.element(document).ready(function(){
    // console.log(1);
    if ($(window).height() > 300) $scope.iframeHeight = $(window).height() - 130;
  });
}]);

faApp.controller('ProductBaseInfoCtrl',['$scope','productService','supplierService','$location','$controller','$routeParams','$filter','companyService','$route',function($scope,productService,supplierService,$location,$controller,$routeParams,$filter,companyService,$route) {
  $controller('BaseCtrl', {$scope: $scope});
  $scope.product = {};
  $scope.pLabelItem = {}
    $scope.proserieslist = [];

  $scope.showProSeriesFlag = false;
  $scope.showXcxsearchnoRecord = false;

  $scope.loading = true;
  $scope.pathText = "修改产品";
  $scope.id = $routeParams.id;
    $scope.tabUrlMap = {
        pronotice: "#/product/pronoticeattach?id=" + $routeParams.id
    };
  $scope.pPublicAreaModel = $scope.publicAreaModel;
  if ($scope.pPublicAreaModel[0].value != "00")$scope.pPublicAreaModel.unshift({value:"00",text:"全国"});
  $scope.companys = [];
  $scope.companysMap = {};

  companyService.companyList().then(function(json){
    $scope.companys = json.list;
    angular.forEach($scope.companys,function(o){
      $scope.companysMap[o.id] = o;
    });
  });

  $scope.supplierListOfProduct = [];
 
  $scope.queryAccessCompany="";
  $scope.$watch('queryAccessCompany',function(){
     supplierService.supplierList({accessCompany:$scope.queryAccessCompany}).then(function(json){
        $scope.supplierListOfProduct = json.list;
      });
  },true);
  $scope.allTjzls = {};
  productService.productQuery($scope.id).then(function(json){
    $scope.product = json.project;
    $scope.t = $scope.product.pType;
    if($scope.product.tjzls!=undefined){
      angular.forEach($scope.product.tjzls.split(","),function(o){
        $scope.allTjzls[o] = true;
      });
    }
    console.log($scope.allTjzls);

    $scope.product.pIssuingScaleTmp = $scope.product.pIssuingScale / 100000000;
    $scope.product.pProgressiveAmountTmp = $scope.product.pProgressiveAmount / 10000;
    $scope.product.pMinimumAmountTmp = $scope.product.pMinimumAmount / 10000;
    $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale / 100000000;
    $scope.product.pSaleTimeStartStr = $filter("date")($scope.product.pSaleTimeStart,"yyyy-MM-dd");
    $scope.product.pRaiseTime = $filter("date")($scope.product.pRaiseTime,"yyyy-MM-dd");
    $scope.product.pLetterTime = $filter("date")($scope.product.pLetterTime,"yyyy-MM-dd");
    $scope.product.pNoticeTime = $filter("date")($scope.product.pNoticeTime,"yyyy-MM-dd");

    $scope.proserieslist = json.fpProjectSeriesList;
    if(json.project.pLabel) {
        var pLabelArr = json.project.pLabel.split(",");
        for(var i =0; i<pLabelArr.length; i++) {
            if (pLabelArr[i] == '23') {
                $scope.pLabelItem.pLabel23 = '23'
            }
            if (pLabelArr[i] == '1') {
                $scope.pLabelItem.pLabel1 = '1'
            }
            if (pLabelArr[i] == '2') {
                $scope.pLabelItem.pLabel2 = '2'
            }
            if (pLabelArr[i] == '3') {
                $scope.pLabelItem.pLabel3 = '3'
            }
            if (pLabelArr[i] == '4') {
                $scope.pLabelItem.pLabel4 = '4'
            }
            if (pLabelArr[i] == '5') {
                $scope.pLabelItem.pLabel5 = '5'
            }
            if (pLabelArr[i] == '6') {
                $scope.pLabelItem.pLabel6 = '6'
            }
            if (pLabelArr[i] == '7') {
                $scope.pLabelItem.pLabel7 = '7'
            }
            if (pLabelArr[i] == '8') {
                $scope.pLabelItem.pLabel8 = '8'
            }
            if (pLabelArr[i] == '9') {
                $scope.pLabelItem.pLabel9 = '9'
            }
            if (pLabelArr[i] == '10') {
                $scope.pLabelItem.pLabel10 = '10'
            }
            if (pLabelArr[i] == '11') {
                $scope.pLabelItem.pLabel11 = '11'
            }
            if (pLabelArr[i] == '12') {
                $scope.pLabelItem.pLabel12 = '12'
            }
            if (pLabelArr[i] == '13') {
                $scope.pLabelItem.pLabel13 = '13'
            }
            if (pLabelArr[i] == '14') {
                $scope.pLabelItem.pLabel14 = '14'
            }
            if (pLabelArr[i] == '15') {
                $scope.pLabelItem.pLabel15 = '15'
            }
            if (pLabelArr[i] == '16') {
                $scope.pLabelItem.pLabel16 = '16'
            }
            if (pLabelArr[i] == '17') {
                $scope.pLabelItem.pLabel17 = '17'
            }
            if (pLabelArr[i] == '18') {
                $scope.pLabelItem.pLabel18 = '18'
            }
            if (pLabelArr[i] == '19') {
                $scope.pLabelItem.pLabel19 = '19'
            }
            if (pLabelArr[i] == '22') {
                $scope.pLabelItem.pLabel22 = '22'
            }
        }
      }

    $scope.product.image = $scope.product.pImageUri;
    $scope.accessNameOfCompany = $scope.product.pAccessName;


    if($scope.product.projectExpandDTO!=undefined){
      $scope.product.peLogoUri=$scope.product.projectExpandDTO.peLogoUri;
      $scope.product.peHomeLogoUri=$scope.product.projectExpandDTO.peHomeLogoUri;
      delete $scope.product.projectExpandDTO;
    }


    delete $scope.product.pSaleTimeStart;
    delete $scope.product.pSaleTimeEnd;
    delete $scope.product.pEstablishmentTime;
    delete $scope.product.pCode;



    $scope.t = $scope.product.pType;


    $scope.loading = false;
  });

  $scope.onSelectChange = function(){
    for (var i=0;i<$scope.supplierListOfProduct.length;i++){
      if($scope.supplierListOfProduct[i]['id'] == $scope.product.pAccessId){
        $scope.accessNameOfCompany = $scope.supplierListOfProduct[i]['accessName'];
        break;
      }
    }
  };

  $scope.save = function(){
    if (!$scope.form.$invalid){

        var pLabel="";
        if($scope.pLabelItem.pLabel23 && $scope.pLabelItem.pLabel23=='23') {
            pLabel+="23,";
        }
        if($scope.pLabelItem.pLabel1 && $scope.pLabelItem.pLabel1=='1') {
            pLabel+="1,";
        }
        if($scope.pLabelItem.pLabel2 && $scope.pLabelItem.pLabel2=='2') {
            pLabel+="2,";
        }
        if($scope.pLabelItem.pLabel3 && $scope.pLabelItem.pLabel3=='3') {
            pLabel+="3,";
        }
        if($scope.pLabelItem.pLabel4 && $scope.pLabelItem.pLabel4=='4') {
            pLabel+="4,";
        }
        if($scope.pLabelItem.pLabel5 && $scope.pLabelItem.pLabel5=='5') {
            pLabel+="5,";
        }
        if($scope.pLabelItem.pLabel6 && $scope.pLabelItem.pLabel6=='6') {
            pLabel+="6,";
        }
        if($scope.pLabelItem.pLabel7 && $scope.pLabelItem.pLabel7=='7') {
            pLabel+="7,";
        }
        if($scope.pLabelItem.pLabel8 && $scope.pLabelItem.pLabel8=='8') {
            pLabel+="8,";
        }
        if($scope.pLabelItem.pLabel9 && $scope.pLabelItem.pLabel9=='9') {
            pLabel+="9,";
        }
        if($scope.pLabelItem.pLabel10 && $scope.pLabelItem.pLabel10=='10') {
            pLabel+="10,";
        }
        if($scope.pLabelItem.pLabel11 && $scope.pLabelItem.pLabel11=='11') {
            pLabel+="11,";
        }
        if($scope.pLabelItem.pLabel12 && $scope.pLabelItem.pLabel12=='12') {
            pLabel+="12,";
        }
        if($scope.pLabelItem.pLabel13 && $scope.pLabelItem.pLabel13=='13') {
            pLabel+="13,";
        }
        if($scope.pLabelItem.pLabel14 && $scope.pLabelItem.pLabel14=='14') {
            pLabel+="14,";
        }
        if($scope.pLabelItem.pLabel15 && $scope.pLabelItem.pLabel15=='15') {
            pLabel+="15,";
        }
        if($scope.pLabelItem.pLabel16 && $scope.pLabelItem.pLabel16=='16') {
            pLabel+="16,";
        }
        if($scope.pLabelItem.pLabel17 && $scope.pLabelItem.pLabel17=='17') {
            pLabel+="17,";
        }
        if($scope.pLabelItem.pLabel18 && $scope.pLabelItem.pLabel18=='18') {
            pLabel+="18,";
        }
        if($scope.pLabelItem.pLabel19 && $scope.pLabelItem.pLabel19=='19') {
            pLabel+="19";
        }
        if($scope.pLabelItem.pLabel22 && $scope.pLabelItem.pLabel22=='22') {
            pLabel+="22";
        }

        console.info("产品标签:"+pLabel)
        if(pLabel && pLabel.substr(pLabel.length-1,1).indexOf(",")>-1) {
            pLabel = pLabel.substr(0, pLabel.length-1);
        }
        $scope.product.pLabel = pLabel;

      $scope.selectTjzls = [];
      var flag = false;
      for (var i in $scope.allTjzls){
        if ($scope.allTjzls[i]){
          flag = true;
          $scope.selectTjzls.push(i);
        }
      }
      if (!flag){
        alert("请勾选提交资料");
        return;
      }
      $scope.product.pIssuingScale = $scope.product.pIssuingScaleTmp * 100000000;
      $scope.product.pProgressiveAmount = $scope.product.pProgressiveAmountTmp * 10000;
      $scope.product.pMinimumAmount = $scope.product.pMinimumAmountTmp * 10000;
      $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale * 100000000;
      if($scope.t != undefined && $scope.t == "02"){
        $scope.product.pInvestOwnerId && ($scope.product.pInvestOwner = $scope.companysMap[$scope.product.pInvestOwnerId]['cShortName']);
      }
      $scope.product.pInvestOwnerId = $scope.product.pInvestOwnerId || -1;
      if($scope.product.pInvestOwnerId == -1 && $scope.t == "02"){
        $scope.product.pInvestOwner = "";
      }

      if ($scope.product.pSizeRatioType && ($scope.product.pSizeRatioExplain == undefined || $scope.product.pSizeRatioExplain == "")){
        $scope.product.pSizeRatioExplain = $filter("pSizeRatioTypeRender")($scope.product.pSizeRatioType);
      }

      $scope.product.tjzls=$scope.selectTjzls.join(",");

      productService.productEdit($scope.product).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.alertNextPage("产品修改成功!");
          //$location.path("/product/list").search({orderBy:"updateDate",orderByTag:"desc"});
          $route.reload();
        }
      });
    }else{
      if (!$scope.product.pSummary){
        alert("请填写产品简介");
      }else alert("请完整填写表单");
    }
  };

  $scope.openSerarnoWin = function () {
      productService.xcxSearchNoRecordList().then(function (json) {

          if (json.statusCode) {
              alert("出错了:" + json.statusCode);
          } else {
              $scope.showXcxsearchnoRecord = true;
              $scope.searchnolist = json.list;
          }
      });
  }
    $scope.getXcxsearchNoRecord = function (d) {
        $scope.product.pXcxSerarnoKeyword = d.keyword;

        $scope.showXcxsearchnoRecord = false;
    }

  // $scope.onUploadFile({
  //   showMessage : function(m){ alert(m); },
  //   onComplete:function(f,response){
  //     if (response.statusCode == "0000") {
  //       $scope.product.image = response.attribute.fileUrl;
  //       $scope.$apply();
  //     } else {
  //       alert('上传失败');
  //     }
  //   }
  // });
  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response,id){
      id--;
      if (response.statusCode == "0000") {
        if(id==0){
          $scope.product.image = response.attribute.fileUrl;
        }else if(id==1){
          $scope.product.peLogoUri= response.attribute.fileUrl;
        }else if(id==2){
          $scope.product.peHomeLogoUri= response.attribute.fileUrl;
        }
        $scope.$apply();
      } else {
        alert('上传失败');
      }
    }
  });

  $scope.selectInvestOwner = function(){
    $scope.product.pInvestOwner = $scope.product.pInvestOwnerId == undefined ? $scope.companysMap[$scope.product.pInvestOwnerId]['cShortName'] : "";
  };

  $scope.changePsizeRatioType = function(){
    if ($scope.product.pSizeRatioType){
      $scope.product.pSizeRatioExplain = $filter("pSizeRatioTypeRender")($scope.product.pSizeRatioType);
    }
  };
}]);

faApp.controller('ProductViewCtrl',['$scope','productService','$location','$controller','$routeParams','$filter','userService','$route',function($scope,productService,$location,$controller,$routeParams,$filter,userService,$route) {
  $controller('ProductBaseCtrl', {$scope: $scope});
  $scope.id = $routeParams.id;
  $scope.projectAnnualRevenue = [];
  $scope.projectRabateList = [];
  $scope.packPrice={};
  productService.productQuery($scope.id).then(function(json){
    $scope.project = json.project;
    $scope.projectAnnualRevenue = json.projectAnnualRevenueList;
    $scope.projectRabateList = json.projectRabateList;
    if($scope.loginStatus.loginName=='admin'){
      $scope.packPrice.packPriceFlag=true;
   
    }else{
      $scope.packPrice.packPriceFlag= json.packPriceFlag;
    }
  });

  $scope.userList = [];
  userService.userList().then(function(json){
    $scope.userRawList = json.list || [];
    angular.forEach($scope.userRawList,function(o){
      if (o.userNickname != $scope.loginStatus.loginName){
        $scope.userList.push(o);
      }
    });

  });

  $scope.transList = [];
  productService.transPermissionList({pProjectId:$scope.id,pageSize:1000}).then(function(json){
    $scope.transList = json.list || [];
  });

  $scope.trans = {pProjectId:$scope.id};
  $scope.save = function(){
    if (!$scope.form.$invalid){
      productService.transPermissionAdd($scope.trans).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.alertNextPage("操作成功");
          parent.location.href = parent.location.href;
          //$route.reload();
        }
      });
    }else{
      alert("请先完整填写表单");
    }

  };

}]);

faApp.controller('ProductSaleProcessCtrl',['$scope','productService','$location','$controller','$routeParams','$filter','$route',function($scope,productService,$location,$controller,$routeParams,$filter,$route) {
  $controller('BaseCtrl', {$scope: $scope});
  $scope.id = $routeParams.id;
  $scope.item = {id:$scope.id};

  $scope.loading = true;
  productService.productQuery($scope.id).then(function(json){
    $scope.loading = false;
    $scope.project = json.project;
    $scope.item.pAllSubscriptionNum = json.project.pAllSubscriptionNum;
    $scope.item.pAllSubscriptionAmountTmp = json.project.pAllSubscriptionAmount/10000;
    $scope.item.pRecruitmentSummary = json.project.pRecruitmentSummary;
    $scope.item.pSaleStatus = json.project.pSaleStatus;
    $scope.item.pSizeRatioType = json.project.pSizeRatioType;
    $scope.item.pSizeRatioExplain = json.project.pSizeRatioExplain;
    $scope.item.pIssuingScale = json.project.pIssuingScale / 10000;
    $scope.item.pPeriods = json.project.pPeriods;
  });

  $scope.changePsizeRatioType = function(){
    if ($scope.item.pSizeRatioType){
      $scope.item.pSizeRatioExplain = $filter("pSizeRatioTypeRender")($scope.item.pSizeRatioType);
    }
  };

  $scope.save = function(){
    if($scope.item.pAllSubscriptionAmountTmp > $scope.item.pIssuingScale){
      alert("已销售总额不能大于单期规模！");
      return;
    }
    if($scope.item.pIssuingScale > ($scope.project.pAllIssuingScale/10000)){
      alert("单期规模不能大于发行规模！");
      return;
    }
    $scope.item.pAllSubscriptionAmount = $scope.item.pAllSubscriptionAmountTmp * 10000;
    $scope.item.pIssuingScale = $scope.item.pIssuingScale * 10000;
    productService.updateSaleProcess($scope.item).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        productService.updateRecruitmentProcess($scope.item).then(function(json){
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }
        });

        productService.productEdit($scope.item).then(function(json){
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }else{
            $scope.alertNextPage("产品修改成功!");
            $route.reload();
          }
        });
      }
    });
  };
}]);

faApp.controller('ProductProfitCtrl',['$scope','productService','$location','$controller','$routeParams','$filter','$timeout',function($scope,productService,$location,$controller,$routeParams,$filter,$timeout) {
  $controller('BaseCtrl', {$scope: $scope});
  $scope.id = $routeParams.id;
  $scope.item = {};
  $scope.projectAnnualRevenue = [];
  $scope.projectRabateList = [];
  $scope.item['pIsAgreement'] = 0;
  $scope.loading = true;
  $scope.project = {};
  $scope.packPrice = {};
  productService.productQuery($scope.id).then(function(json){
    $scope.project = json.project;
  });
  productService.productProfitList($scope.id).then(function(json){
    $scope.loading = false;
    $scope.projectAnnualRevenue = json.projectAnnualRevenue;
    $scope.projectRabateList = json.projectRabateList;

    if($scope.loginStatus.loginName=='admin'){
      $scope.packPrice.packPriceFlag=true;
   
    }else{
      $scope.packPrice.packPriceFlag= json.packPriceFlag;
    }
  });
  function queryEditLog(){
      productService.productProfitLogList($scope.id).then(function(json){
        $scope.loading = false;
        $scope.logList = json.logList;
      });
  }
  queryEditLog();
  $scope.edit = function(v){
    $scope.itemIndex = v;
    $scope.item['pIsAgreement'] = $scope.projectRabateList[v]['pIsAgreement'];
    $scope.item['pStartAmount'] = $scope.projectAnnualRevenue[v]['pStartAmount'] / 10000;
    $scope.item['pEndAmount'] = $scope.projectAnnualRevenue[v]['pEndAmount'] / 10000;
    $scope.item['pAnnualRevenueExpect'] = $scope.projectAnnualRevenue[v]['pAnnualRevenueExpect'];
    $scope.item['pRabateProfit'] = $scope.projectRabateList[v]['pRabateProfit'];
    $scope.item['pCorePrice'] = $scope.projectRabateList[v]['pCorePrice'];
    $scope.item['pCostPrice'] = $scope.projectRabateList[v]['pCostPrice'];
    $scope.item['pSellingPrice'] = $scope.projectRabateList[v]['pSellingPrice'];
    $scope.item['pCostBackPrice'] = $scope.projectRabateList[v]['pCostBackPrice'];
    $scope.item['pCoreBackPrice'] = $scope.projectRabateList[v]['pCoreBackPrice'];
    $scope.item['pBackSellingPrice'] = $scope.projectRabateList[v]['pBackSellingPrice'];
    $scope.item['pBackRabateProfit'] = $scope.projectRabateList[v]['pBackRabateProfit'];
  };

  $scope.deleteItem = function(v){
    if ($scope.projectRabateList.length <= 1){
      alert("最后一个不能删除");
      return;
    }

    $scope.projectAnnualRevenue.splice(v,1);
    $scope.projectRabateList.splice(v,1);
    if (v > $scope.itemIndex){
      $scope.itemIndex --;
    }

    $scope.edit(0);
    $timeout(function(){
      $scope.save();
    },10);
  };

  $scope.changePrice = function(v){
      if(v==1){
        $scope.item.pCostPrice =$scope.item.pCorePrice;
        $scope.item.pSellingPrice =$scope.item.pCorePrice;
        $scope.item.pRabateProfit =$scope.item.pCorePrice;
      }else if(v==2){
        $scope.item.pCostBackPrice =$scope.item.pCoreBackPrice;
        $scope.item.pBackSellingPrice =$scope.item.pCoreBackPrice;
        $scope.item.pBackRabateProfit =$scope.item.pCoreBackPrice;
      }
  };

  $scope.save = function(){
    if ($scope.form.$invalid){
      alert("请填写完整信息！");
      return;
    }
    var v = $scope.itemIndex;
    if (v == undefined){
      if ($scope.projectRabateList.length < 1){
        v = 0;
      }else{
        v = $scope.projectAnnualRevenue.length;
      }
      $scope.projectRabateList[v] = {};
      $scope.projectAnnualRevenue[v] = {pId:$scope.id};
    }

    // $scope.projectRabateList[v]['pRabateProfit'] = $scope.item['pRabateProfit'];
    // $scope.projectRabateList[v]['pCorePrice'] = $scope.item['pCorePrice'];
    // $scope.projectRabateList[v]['pCostPrice'] = $scope.item['pCostPrice'];
    // $scope.projectRabateList[v]['pSellingPrice'] = $scope.item['pSellingPrice'];
    // $scope.projectRabateList[v]['pCostBackPrice']=$scope.item['pCostBackPrice'];
    // $scope.projectRabateList[v]['pCoreBackPrice']=$scope.item['pCoreBackPrice'];
    // $scope.projectRabateList[v]['pBackSellingPrice']=$scope.item['pBackSellingPrice'];
    // $scope.projectRabateList[v]['pBackRabateProfit']=$scope.item['pBackRabateProfit'];

    // $scope.projectAnnualRevenue[v]['pStartAmount'] = $scope.item['pStartAmount'] * 10000;
    // $scope.projectAnnualRevenue[v]['pEndAmount'] = $scope.item['pEndAmount'] ? ($scope.item['pEndAmount'] * 10000 ) : $scope.project.pIssuingScale;
    // $scope.projectAnnualRevenue[v]['pAnnualRevenueExpect'] = $scope.item['pAnnualRevenueExpect'];
    // $scope.projectRabateList[v]['pIsAgreement'] = $scope.item['pIsAgreement'] || 0;

    $scope.projectRabateList[v]['pIsAgreement'] = $scope.item['pIsAgreement'] || 0;
    $scope.projectAnnualRevenue[v]['pStartAmount'] = $scope.item['pStartAmount'] * 10000;
    $scope.projectAnnualRevenue[v]['pEndAmount'] = $scope.item['pEndAmount'] ? ($scope.item['pEndAmount'] * 10000 ) : $scope.project.pIssuingScale;
    $scope.projectAnnualRevenue[v]['pAnnualRevenueExpect'] = $scope.item['pAnnualRevenueExpect'];
    // 如果是协议价   把挂网价等价格 置为0
    if($scope.projectRabateList[v]['pIsAgreement']==1){
      $scope.projectRabateList[v]['pRabateProfit']=0;
      $scope.projectRabateList[v]['pCorePrice']=0;
      $scope.projectRabateList[v]['pCostPrice']=0;
      $scope.projectRabateList[v]['pSellingPrice']=0;
      $scope.projectRabateList[v]['pCostBackPrice']=0;
      $scope.projectRabateList[v]['pCoreBackPrice']=0;
      $scope.projectRabateList[v]['pBackSellingPrice']=0;
      $scope.projectRabateList[v]['pBackRabateProfit']=0;
    }else{
      $scope.projectRabateList[v]['pRabateProfit'] = $scope.item['pRabateProfit'];
      $scope.projectRabateList[v]['pCorePrice'] = $scope.item['pCorePrice'];
      $scope.projectRabateList[v]['pCostPrice'] = $scope.item['pCostPrice'];
      $scope.projectRabateList[v]['pSellingPrice'] = $scope.item['pSellingPrice'];
      $scope.projectRabateList[v]['pCostBackPrice']=$scope.item['pCostBackPrice'];
      $scope.projectRabateList[v]['pCoreBackPrice']=$scope.item['pCoreBackPrice'];
      $scope.projectRabateList[v]['pBackSellingPrice']=$scope.item['pBackSellingPrice'];
      $scope.projectRabateList[v]['pBackRabateProfit']=$scope.item['pBackRabateProfit'];

      //20180408   核心价和后端核心价后端成本价前台隐藏，给默认值
      $scope.projectRabateList[v]['pCorePrice']=$scope.projectRabateList[v]['pCostPrice'];
      $scope.projectRabateList[v]['pCoreBackPrice']=$scope.projectRabateList[v]['pCostPrice'];
      $scope.projectRabateList[v]['pCostBackPrice']=$scope.projectRabateList[v]['pCostPrice'];
    }


    $scope.formData = {pId:[],pRebateType:[],pStartAmount:[],pEndAmount:[],pAnnualRevenueExpect:[],pIsAgreement:[],pRabateProfit:[],pCorePrice:[],pCostPrice:[],pSellingPrice:[],pCostBackPrice:[],pCoreBackPrice:[],pBackSellingPrice:[],pBackRabateProfit:[] };
    angular.forEach($scope.projectAnnualRevenue,function(o,i){
      $scope.formData['pId'].push(o['pId']);
      $scope.formData['pRebateType'].push("01");
      $scope.formData['pStartAmount'].push(o['pStartAmount']);
      $scope.formData['pEndAmount'].push(o['pEndAmount']);
      $scope.formData['pAnnualRevenueExpect'].push(o['pAnnualRevenueExpect']);
      $scope.formData['pRabateProfit'].push($scope.projectRabateList[i]['pRabateProfit'] || 0);
      $scope.formData['pCorePrice'].push($scope.projectRabateList[i]['pCorePrice'] || 0);
      $scope.formData['pCostPrice'].push($scope.projectRabateList[i]['pCostPrice'] || 0);
      $scope.formData['pSellingPrice'].push($scope.projectRabateList[i]['pSellingPrice'] || 0);
      $scope.formData['pCostBackPrice'].push($scope.projectRabateList[i]['pCostBackPrice'] || 0);
      $scope.formData['pCoreBackPrice'].push($scope.projectRabateList[i]['pCoreBackPrice'] || 0);
      $scope.formData['pBackSellingPrice'].push($scope.projectRabateList[i]['pBackSellingPrice'] || 0);
      $scope.formData['pBackRabateProfit'].push($scope.projectRabateList[i]['pBackRabateProfit'] || 0);

      $scope.formData['pIsAgreement'].push($scope.projectRabateList[i]['pIsAgreement']);
    });

    $scope.formData2 = {id:$scope.id};
    for (k in $scope.formData){
      $scope.formData2[k] = $scope.formData[k].join(",");
    }
    console.log($scope.formData2);
    productService.productProfitUpdate($scope.formData2).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("操作成功");
        $scope.item = {};
        $scope.item.pIsAgreement = "0";
        $scope.itemIndex = undefined;

        //刷新日志
        queryEditLog();
      }
    });
  };
}]);

faApp.controller('ProductAttachCtrl',['$scope','productService','$location','$controller','$routeParams','$filter',function($scope,productService,$location,$controller,$routeParams,$filter) {
  $controller('BaseCtrl', {$scope: $scope});
  $scope.id = $routeParams.id;
  $scope.item = {};
  $scope.attachs = [];

  $scope.loading = true;
  productService.productQuery($scope.id).then(function(json){
    $scope.project = json.project;
  });
  productService.productAttachList($scope.id).then(function(json){
    $scope.loading = false;
    $scope.attachs = json.projectAttachmentsList;
  });

  $scope.edit = function(v){
    $scope.itemIndex = v;
    $scope.item['fName'] = $scope.attachs[v]['fName'];
    $scope.item['fileUrl'] = $scope.attachs[v]['fPath'];
    $scope.item['fileType'] = $scope.attachs[v]['fType'];
  };

  $scope.deleteItem = function(v){
    $scope.attachs.splice(v,1);
    if (v > $scope.itemIndex){
      $scope.itemIndex --;
    }
    $scope.save(true);
  };

  $scope.save = function(deleteFlag){
    if (!deleteFlag){
      var v = $scope.itemIndex;
      if (v == undefined){
        if ($scope.attachs.length < 1){
          v = 0;
        }else{
          v = $scope.attachs.length;
        }
        $scope.attachs[v] = {pId:$scope.id};
      }
      $scope.attachs[v]['fName'] = $scope.item['fName'];
      $scope.attachs[v]['fPath'] = $scope.item['fileUrl'];
      $scope.attachs[v]['fType'] = $scope.item['fileType'];
    }

    $scope.formData = {fName:[],fileUrl:[],fileType:[]};
    angular.forEach($scope.attachs,function(o,i){
      if (o['fName'] && o['fPath'] && o['fType']){
        $scope.formData['fName'].push(o['fName']);
        $scope.formData['fileUrl'].push(o['fPath']);
        $scope.formData['fileType'].push(o['fType']);
      }
    });


    $scope.formData2 = {pId:$scope.id};
    for (k in $scope.formData){
      $scope.formData2[k] = $scope.formData[k].join(",");
    }

    productService.productAttachUpdate($scope.formData2).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.addAlert("操作成功");
        $scope.item = {};
        $scope.itemIndex = undefined;
      }
    });
  };

  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    type:'productFile',
    refid:$scope.id,
    onComplete:function(f,response){
      if (response.statusCode == "0000") {
        $scope.item.fileUrl = response.attribute.fileUrl;
        $scope.item.fileType = response.attribute.fileType;
        $scope.item.fName = response.attribute.fName;
        $scope.$apply();
      } else if (response.statusCode == "0003") {
        alert('格式不正确');
      } else {
        alert('上传失败');
      }
    }
  });
}]);


faApp.controller('ProductNoiceCtrl',['$scope','productService','$location','$controller','$routeParams','$filter',function($scope,productService,$location,$controller,$routeParams,$filter) {
    $controller('BaseCtrl', {$scope: $scope});
    $scope.id = $routeParams.id;
    console.info("产品ID："+$scope.id)

    $scope.item = {};
    $scope.attachs = [];

    $scope.loading = true;
    productService.productQuery($scope.id).then(function(json){
        $scope.project = json.project;
    });

    queryFileList();//查询附件信息
    function queryFileList() {
        productService.productNoticeQuery({"refid":$scope.id, "type":"productNotice"}).then(function(json){
          console.info("产品公告附件：")
          console.info(json.list)

            $scope.loading = false;
            $scope.attachs = json.list;
        });
    }

    $scope.deleteItem = function(d, index){

        if(d.id) {
            $scope.loading = true;
            productService.productNoticeDelete({id:d.id}).then(function (json) {
              if(json.statusCode=='2002') {
                alert("参数缺失!");
              } else {
                  $scope.attachs.splice(index, 1);

                  $scope.loading = false;
                  $scope.addAlert("删除成功");
              }
            });
        }
    };

    $scope.onUploadFile({
        showMessage : function(m){ alert(m); },
        type:'productNotice',
        refid:$scope.id,
        onComplete:function(f,response){
            if (response.statusCode == "0000") {
                // $scope.item.fileUrl = response.attribute.fileUrl;
                // $scope.item.fileType = response.attribute.fileType;
                // $scope.item.fName = response.attribute.fName;
                // $scope.$apply();
                queryFileList();
            } else if (response.statusCode == "0003") {
                alert('格式不正确');
            } else {
                alert('上传失败');
            }
        }
    });
}]);

faApp.controller('ProductChooseRecommendList',['$scope','productService','$location','$controller','$route','adService','$routeParams',function($scope,productService,$location,$controller,$route,adService, $routeParams) {
  $controller('BaseListCtrl', {$scope: $scope});

  $scope.recommendList = [];

  $scope.$watch('config',function(){
    adService.adRecommendList($scope.config).then(function(json){
      $scope.recommendList = json.list;
      // $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true);

  $scope.config = {
    "pageSize" : 100,
    "pageNo" : 1,
    "advertPosition" : $routeParams.t || '10'
  };

  $scope.toAddRecommend = function(){
    if($scope.recommendList && $scope.recommendList.length >= 5){
      alert("最多能有五项！");
      return;
    }else{
      $location.path("/chooseRecommend/add").search({t : $scope.config.advertPosition || '10'});
    }
  }

  $scope.start = function(id){
    adService.adStart({id:id,status:"01"}).then(function(json){
      $route.reload();
    });
  };

  $scope.stop = function(id){
    var t = 0;
    angular.forEach($scope.recommendList,function(o){
      if(o.status == '01')
        t++;
    });
    if(t <= 2){
      alert("最少得有两项！");
      return;
    }
    adService.adStop({id:id,status:"02"}).then(function(json){
      $route.reload();
    });
  };

}]);

faApp.controller('ProductChooseRecommendAdd', ['$scope', 'productService', '$location', '$controller', '$route', 'adService', '$routeParams', function($scope, productService, $location, $controller, $route, adService, $routeParams) {
  $controller('BaseListCtrl', { $scope: $scope });

  $scope.recommend = {
    title:'',
    pic:'',
    linkAddre:'',
    startTime:'1990-01-01 00:00:00',
    endTime:'3000-01-01 23:59:59',
    status:'01',
    advertSort:'1',
    picAddre:'',
    advertPosition: $routeParams.t || '10'
  };

  $scope.save = function(){
    if (!$scope.form.$invalid){
      if(!$scope.recommend.picAddre && $scope.recommend.advertPosition != '14'){
        alert("请上传图片!");
        return;
      }
      adService.adAdd($scope.recommend).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/chooseRecommend/list").search({t : $scope.recommend.advertPosition});
        }
      });
    }else{
      alert("请把信息填写完整！");
    }
  }

  $scope.onUploadFile({
    showMessage: function(m) { alert(m); },
    onComplete: function(f, response, id) {
      if (response.statusCode == "0000") {
        $scope.recommend.picAddre = response.attribute.fileUrl;
        $scope.$apply();
      } else {
        alert('上传失败');
      }
    }
  });

}]);

faApp.controller('ProductChooseRecommendEdit', ['$scope', 'productService', '$location', '$controller', '$route', 'adService', '$routeParams','$filter' , function($scope, productService, $location, $controller, $route, adService, $routeParams, $filter) {
  $controller('BaseListCtrl', { $scope: $scope });

  $scope.recommend = {};
  $scope.id = $routeParams.id;

  if($scope.id){
    adService.adQuery($scope.id).then(function(json){
      $scope.recommend = json.dto;

      $scope.recommend.startTime = $filter("date")($scope.recommend.startTime,"yyyy-MM-dd") + " 00:00:00";;
      $scope.recommend.endTime = $filter("date")($scope.recommend.endTime,"yyyy-MM-dd") + " 23:59:59";
    });
  }

  $scope.save = function(){
    if (!$scope.form.$invalid){
      if(!$scope.recommend.picAddre && $scope.recommend.advertPosition != '14'){
        alert("请上传图片!");
        return;
      }
      adService.adEdit($scope.recommend).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/chooseRecommend/list").search({t : $scope.recommend.advertPosition});
        }
      });
    }else{
      alert("请把信息填写完整！");
    }
  }

  $scope.onUploadFile({
    showMessage: function(m) { alert(m); },
    onComplete: function(f, response, id) {
      if (response.statusCode == "0000") {
        $scope.recommend.picAddre = response.attribute.fileUrl;
        $scope.$apply();
      } else {
        alert('上传失败');
      }
    }
  });
}]);

faApp.controller('ProductVideoCtrl',['$scope','productService','roadVideoService','$location','$controller','$routeParams','$filter','$route',function($scope,productService,roadVideoService,$location,$controller,$routeParams,$filter,$route) {

  $controller('BaseCtrl', {$scope: $scope});
  $scope.id = $routeParams.id;
  $scope.spnr = {};
  $scope.player = '';

  roadVideoService.list({isProduct:'0',pageSize:1000,pageNo:1}).then(function(json){
    $scope.list = json.list;
  });
  productService.productQuery($scope.id).then(function(json){
    $scope.product = json.project;
    $scope.videoInfoPost = {
      productType:$scope.product.pType,
      productId:$scope.product.id
    };
    roadVideoService.videoIdbyPro($scope.videoInfoPost).then(function(json){
      $scope.oldId = json.dto ? json.dto.id : '';
      $scope.title = json.dto ? json.dto.title : '';

    });
  });



  $scope.save=function(){
    if($scope.newVideoId==null||$scope.newVideoId==''){
      alert("视频名称不能为空");
      return ;
    }
    $scope.spnr.productType=$scope.product.pType;
    $scope.spnr.productId=$scope.id;
    $scope.spnr.id = $scope.newVideoId;
    $scope.spnr.oldId = $scope.oldId;
    roadVideoService.edit($scope.spnr).then(function(json){
      if(!json.statusCode){
        alert("修改成功");
        $route.reload()
      }else{
        alert(json.statusCode);
      }
    });
  }

  $scope.playVideo = function(v){
    if(!v){
      alert('请选择视频');
      return;
    }else{
      for( arr in $scope.list){
        if($scope.list[arr].id == v){
          $scope.videoId = $scope.list[arr].videoId;
        }
      };
    };
    if($scope.videoId){
      $scope.showPlayBox = true;
      $scope.player = new YKU.Player('youkuplayer',{
        styleid: '0',
        client_id: YK_CLIENT_ID,
        vid: $scope.videoId,
        newPlayer: true
      })
    }
  }
  $scope.stopPlay = function(){
    $scope.videoId = '';
    $scope.showPlayBox = false;
  }




}]);
